<template>
  <div class="dashboard-container">
    <div class="full-screen-image">
      <el-image
        :src="outSide"
        :zoom-rate="1.2"
        :max-scale="7"
        :min-scale="0.2"
        :initial-index="0"
        fit="fill"
        class="full-screen-img"
        @click="handleImageClick"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Dashboard",
  inheritAttrs: false,
});
const outSide = ref(new URL("../../assets/images/outSide.png", import.meta.url).href);
const baseHeight = ref("100vh");

import router from "@/router";

import { useUserStore } from "@/store/modules/user";
import StatsAPI, { VisitStatsVO } from "@/api/system/log";
import NoticeAPI, { NoticePageVO } from "@/api/system/notice";

interface VisitStats {
  title: string;
  icon: string;
  tagType: "primary" | "success" | "warning";
  growthRate: number;
  // 粒度
  granularity: string;
  // 今日数量
  todayCount: number;
  totalCount: number;
}

const noticeDetailRef = ref();
// const imageStyle = computed(() => {
//   const vh = window.innerHeight * 0.01;
//   console.log("vh", vh - 8000);
//   return {
//     height: `${vh - 8000}px`,
//     width: "100%",
//   };
// });

const userStore = useUserStore();
const date: Date = new Date();
const greetings = computed(() => {
  const hours = date.getHours();
  if (hours >= 6 && hours < 8) {
    return "晨起披衣出草堂，轩窗已自喜微凉🌅！";
  } else if (hours >= 8 && hours < 12) {
    return "上午好，" + userStore.userInfo.nickname + "！";
  } else if (hours >= 12 && hours < 18) {
    return "下午好，" + userStore.userInfo.nickname + "！";
  } else if (hours >= 18 && hours < 24) {
    return "晚上好，" + userStore.userInfo.nickname + "！";
  } else {
    return "偷偷向银河要了一把碎星，只等你闭上眼睛撒入你的梦中，晚安🌛！";
  }
});

const onlineUserCount = ref(0);

const visitStatsLoading = ref(true);
const visitStatsList = ref<VisitStats[] | null>(Array(3).fill({}));

// 加载访问统计数据
const loadVisitStatsData = async () => {
  const list: VisitStatsVO[] = await StatsAPI.getVisitStats();

  if (list) {
    const tagTypes: ("primary" | "success" | "warning")[] = ["primary", "success", "warning"];
    const transformedList: VisitStats[] = list.map((item, index) => ({
      title: item.title,
      icon: getVisitStatsIcon(item.type),
      tagType: tagTypes[index % tagTypes.length],
      growthRate: item.growthRate,
      granularity: "日",
      todayCount: item.todayCount,
      totalCount: item.totalCount,
    }));
    visitStatsList.value = transformedList;
    visitStatsLoading.value = false;
  }
};

// 格式化增长率
const formatGrowthRate = (growthRate: number): string => {
  if (growthRate === 0) {
    return "-";
  }

  const formattedRate = Math.abs(growthRate * 100)
    .toFixed(2)
    .replace(/\.?0+$/, "");
  return formattedRate + "%";
};

/** 获取增长率文本颜色类 */
const getGrowthRateClass = (growthRate: number): string => {
  if (growthRate > 0) {
    return "color-[--el-color-danger]";
  } else if (growthRate < 0) {
    return "color-[--el-color-success]";
  } else {
    return "color-[--el-color-info]";
  }
};

/** 获取访问统计图标 */
const getVisitStatsIcon = (type: string) => {
  switch (type) {
    case "pv":
      return "pv";
    case "uv":
      return "uv";
    case "ip":
      return "ip";
    default:
      return "pv";
  }
};

const notices = ref<NoticePageVO[]>([]);

// 查看更多
function viewMoreNotice() {
  router.push({ path: "/myNotice" });
}

// 阅读通知公告
function viewNoticeDetail(id: string) {
  noticeDetailRef.value.openNotice(id);
}

const handleImageClick = (event: MouseEvent) => {
  const element = event.target as HTMLElement;
  if (element.requestFullscreen) {
    element.requestFullscreen();
  } else {
    console.warn("Fullscreen is not supported in this browser.");
  }
};

const handleKeydown = (event: KeyboardEvent) => {
  if (event.key === "Escape" || event.key === "Esc") {
    if (document.fullscreenElement) {
      document.exitFullscreen().catch((err) => {
        console.error(`Error attempting to exit full-screen mode: ${err.message} (${err.name})`);
      });
    }
  }
};

onMounted(() => {
  // loadVisitStatsData();

  // 获取我的通知公告
  // NoticeAPI.getMyNoticePage({ pageNum: 1, pageSize: 10 }).then((data) => {
  //   notices.value = data.list;
  // });

  // WebSocketManager.subscribeToTopic("/topic/onlineUserCount", (data) => {
  //   console.log("收到在线用户数量：", data);
  //   onlineUserCount.value = JSON.parse(data);
  // });

  window.addEventListener("keydown", handleKeydown);
});

onUnmounted(() => {
  window.removeEventListener("keydown", handleKeydown);
});
</script>

<style lang="scss" scoped>
.dashboard-container {
  position: relative;
  padding: 24px;

  .full-screen-image {
    position: absolute;
    top: 10px;
    left: 10px;
    width: 88vw;
    height: 88vh;
    padding: 0;
    margin: 0;
    overflow: hidden;
  }

  .full-screen-img {
    width: 100%;
    height: 100%;
    cursor: pointer;
    object-fit: cover; /* 保持图片的宽高比并填充整个容器 */
  }

  .github-corner {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 1;
    border: 0;
  }
}
</style>
